<template>
    <main ref="main">
        <mdui-top-app-bar>
            <mdui-button-icon @click="back">
                <SvgIcon :path="mdiChevronLeft" type="mdi" />
            </mdui-button-icon>
            <mdui-top-app-bar-title>编辑 <span>{{ word_sheer_name }}</span> 中的单词</mdui-top-app-bar-title>
            <div style="flex-grow: 1"></div>
            <div>
                <mdui-button variant="tonal" :class="{ mm_all_btn: true, more_border_all: isManyManage }"
                    @click="chall">反选</mdui-button>
                <mdui-button variant="tonal" :class="{ mm_rem_btn: true, more_rem_btn: isManyManage }"
                    @click="removeAll">删除</mdui-button>
                <mdui-button variant="elevated" @click="isManyManage = !isManyManage"
                    :class="{ mm_btn: true, more_border_btn: isManyManage }">批量管理</mdui-button>

            </div>
            <mdui-button @click="SaveAll">保存
                <SvgIcon slot="icon" :path="mdiContentSave" type="mdi" />
            </mdui-button>
        </mdui-top-app-bar>
        <mdui-bottom-app-bar>


            <div style="flex-grow: 1"></div>
            <mdui-fab @click="creatWordItem">
                <SvgIcon slot="icon" :path="mdiPlus" type="mdi" />
            </mdui-fab>
        </mdui-bottom-app-bar>
        <mdui-card v-for="(words, index) in words" :key="words._id" class="list-item-woed" ref="wordsItems"
            :class="{ highlight: words.data.length > 0 ? false : true }" @click="nowFoc = index">


            <div :class="{ 'left-btn': true, 'left-btn-hide': isManyManage }">
                <mdui-checkbox :value="words._id" ref="checkbox_items"></mdui-checkbox>
            </div>
            <div :class="{ 'content': true, 'content-is-mm': isManyManage }">
                <div class="mdui-list-item-woed" v-for="(item, index) in words.data" :key="item._id">
                    <mdui-button-icon style="transform: scale(0.8);" @click="remove_word(words._id, item._id)">
                        <SvgIcon :path="mdiWindowClose" type="mdi" />
                    </mdui-button-icon>
                    <mdui-chip elevated @click="chnageWord(words._id, item._id, 'trans')">{{ item.trans }}</mdui-chip>
                    <mdui-chip elevated @click="chnageWord(words._id, item._id, 'word')">{{ item.word
                        }}</mdui-chip>
                </div>
            </div>
            <div class="right-btn"
                :style="{ opacity: isManyManage ? '0' : '1', filter: isManyManage ? 'blur(5px)' : 'none' }">
                <mdui-button-icon @click="add_word(words._id)">
                    <SvgIcon :path="mdiPlus" type="mdi" />
                </mdui-button-icon>
                <mdui-button-icon @click="remove_word_item(words._id)">
                    <SvgIcon :path="mdiDelete" type="mdi" />
                </mdui-button-icon>


            </div>
        </mdui-card>
        <div class="bor" ref="bor"></div>
    </main>

    <mdui-dialog close-on-esc close-on-overlay-click :open="isOpenAddWordDialog" @close="isOpenAddWordDialog = false">
        <span slot="headline">添加单词</span>
        <span slot="description">请输入单词和翻译</span>

        <mdui-text-field label="单词" @input="creatWordDialoginputData.word = $event.target.value" @keydown="nextF"
            style="margin-bottom: 10px;" :value="creatWordDialoginputData.word" autofocus></mdui-text-field>
        <mdui-text-field label="翻译" @keydown="nextF($event, () => creatWord(creatWordDialoginputData, add_word_id))"
            @input="creatWordDialoginputData.trans = $event.target.value"
            :value="creatWordDialoginputData.trans"></mdui-text-field>
        <mdui-button slot="action" variant="text" @click="isOpenAddWordDialog = false">取消</mdui-button>
        <mdui-button slot="action" variant="text"
            @click="creatWord(creatWordDialoginputData, add_word_id)">添加</mdui-button>
    </mdui-dialog>

</template>

<script setup>
import { ref, onMounted, reactive, watch, onUnmounted } from 'vue'
import { useRoute } from 'vue-router'
import { snackbar } from 'mdui/functions/snackbar.js';
import SvgIcon from '@jamescoyle/vue-icon'
import { mdiChevronLeft, mdiPlus, mdiDelete, mdiWindowClose, mdiContentSave } from '@mdi/js'
import { prompt } from "mdui/functions/prompt.js";
import { confirm } from 'mdui/functions/confirm.js';
import { isEqual,nextF } from '@/assets/helper';
import router from '@/router';
const route = useRoute()
const id = route.params.id
const word_sheer_name = ref('')
const main = ref(null)
const checkbox_items = ref(null)
const isOpenAddWordDialog = ref(false)
const isManyManage = ref(false)
const add_word_id = ref(null)
const words = reactive([
]);
const nowFoc = ref(null)
const wordsItems = ref(null)
const bor = ref(null)
const creatWordDialoginputData = ref({
    word: '',
    trans: ''
})
let nowKes = []
const keydown = (e) => {
    if (e.repeat) {
        return
    }
    nowKes.push(e.key)
    kec.forEach(item => {
        if (isEqual(nowKes, item.keys)) {
            item.callback()
        }
    })

}
const keyup = (e) => {
    nowKes.pop()
}
window.addEventListener('keydown', keydown)
window.addEventListener('keyup', keyup)


const kec = [
    {
        keys: ["Control", "ArrowUp"],
        callback: () => {
            if (nowFoc.value != null) {
                if (nowFoc.value - 1 < 0) {
                    nowFoc.value = 0
                } else {
                    nowFoc.value--


                }
            } else {
                nowFoc.value = 0
            }
        }
    },
    {
        keys: ["Control", "ArrowDown"],
        callback: () => {
            if (nowFoc.value != null) {
                if (nowFoc.value + 1 > wordsItems.value.length - 1) {
                    nowFoc.value = 0
                } else {
                    nowFoc.value++

                }
            } else {
                nowFoc.value = 0
            }
        }
    },
    {
        keys: ["Control", "i"],
        callback: () => {
            creatWordItem()
            setTimeout(() => {
                nowFoc.value = wordsItems.value.length - 1
            }, 0)
        }
    },
    {
        keys: ["Shift", "Delete"],
        callback: () => {
            words.splice(nowFoc.value, 1)

            // 移动nowFoc到上一个或下一个
            if (nowFoc.value == words.length) {
                nowFoc.value--
            } else if (nowFoc.value == -1) {
                nowFoc.value = 0
            }

        }
    },
    {
        keys: ["+"],
        callback: () => {
            add_word(words[nowFoc.value]._id)
        }
    }
]
onUnmounted(() => {
    window.removeEventListener('keydown', keydown)
    window.removeEventListener('keyup', keyup)
})
onMounted(() => {
    console.log(id)
    fetch(`${window.server}/api/get_words`, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify({ id })

    })
        .then(response => response.json())
        .then(data => {
            if (data.message === "Success") {
                console.log(data)
                word_sheer_name.value = data.name
                words.splice(0, words.length) // 清空原有的单词列表
                data.words.forEach(item => {
                    words.push({
                        _id: item._id,
                        data: item.data
                    })
                })
                if (words.length > 0) {
                    setTimeout(() => {
                        nowFoc.value = 0
                    }, 50)
                }
            } else {
                snackbar({
                    message: data.message || "获取单词失败",
                });
            }
        })
        .catch(error => {
            console.error("请求错误:", error)
            snackbar({
                message: "请求错误，请稍后再试",
            });
        })
})
watch(isOpenAddWordDialog, (newData) => {
    if (!newData) {
        creatWordDialoginputData.value = {
            word: '',
            trans: ''
        }


        add_word_id.value = null
    }
})

watch(nowFoc, (newData) => {
    console.log(newData);

    if (newData < 0) {
        bor.value.animate([
            {}, {
                //left: 0 + 'px',
                //top: ele.offsetTop + 'px',
                transform: 'translateY(0px)',
                width: 0 + '%',
                height: 0 + 'px'
            }
        ], {
            duration: 400,
            fill: 'forwards',
            easing: 'cubic-bezier(0.34, 1.56, 0.64, 1)'
        })
        return
    }
    const ele = wordsItems.value[newData]
    // 滚动

    main.value.scroll({
        left: 0,
        top: ele.offsetTop - 100,
        behavior: "smooth"
    })

    // 获取ele相对于main的rect位置
    const eleRect = ele.getBoundingClientRect()

    bor.value.animate([
        {}, {
            //left: 0 + 'px',
            //top: ele.offsetTop + 'px',
            transform: 'translateY(' + ele.offsetTop + 'px)',
            width: 100 + '%',
            height: eleRect.height + 'px'
        }
    ], {
        duration: 400,
        fill: 'forwards',
        easing: 'cubic-bezier(0.34, 1.56, 0.64, 1)'
    })
})
const back = () => {
    SaveAll().then(() => {
        router.back();
    }).catch(() => {
    });

}
const creatWordItem = () => {

    words.push({
        _id: Date.now(),
        data: []
    })

    // 滚动到最底部
    setTimeout(() => {
        main.value.scrollTop = main.value.scrollHeight;
        nowFoc.value = words.length - 1;
    }, 10);
}

const creatWord = (data, id) => {
    if (data.word && data.trans) {
        if (id) {
            // 查找id
            let index = words.findIndex(item => item._id === id)
            data._id = Date.now()
            words[index].data.push(data)
            isOpenAddWordDialog.value = false
            if (nowFoc.value == index) {
                console.log("index");


                setTimeout(() => {
                    bor.value.animate([{}, {
                        height: wordsItems.value[nowFoc.value].offsetHeight + 'px'
                    }],
                        { duration: 300, fill: 'forwards', easing: 'cubic-bezier(0.34, 1.56, 0.64, 1)' })
                }, 10);
            }
        }
    } else { snackbar({ message: "请输入单词和翻译" }); }
}

const remove_word_item = (id) => {
    confirm({
        headline: "删除单词",
        description: "确定要删除单词吗？",
        confirmText: "删除",
        cancelText: "取消",
        onConfirm: () => {
            // 查找单词的index
            let index = words.findIndex(item => item._id === id)


            words.splice(index, 1)

            // 移动nowFoc到上一个或下一个
            if (index == words.length) {
                nowFoc.value--
            } else if (nowFoc.value == -1) {
                nowFoc.value = 0
            } else if (index == 0) {
                nowFoc.value = -1
            }

        },
    })


}

const remove_word = (wid, id) => {
    const wordItem = words.find(item => item._id === wid);
    if (wordItem) {
        const index = wordItem.data.findIndex(item => item._id === id);
        if (index !== -1) {
            wordItem.data.splice(index, 1);
            if (wordItem.data.length === 0) {
                words.splice(words.findIndex(item => item._id === wid), 1);
            }
        } else {
            snackbar({
                message: "单词未找到",
            });
        }
        if (nowFoc.value == index) {
            console.log("index");


            setTimeout(() => {
                bor.value.animate([{}, {
                    height: wordsItems.value[nowFoc.value].offsetHeight + 'px'
                }],
                    { duration: 300, fill: 'forwards', easing: 'cubic-bezier(0.34, 1.56, 0.64, 1)' })
            }, 50);
        }
    } else {
        snackbar({
            message: "单词组未找到",
        });
    }

}

const add_word = (id) => {
    isOpenAddWordDialog.value = true
    add_word_id.value = id
}

const chall = () => {
    if (!checkbox_items.value) {
        snackbar({
            message: "没有可选的单词",
        });
        isManyManage.value = false; // 取消批量管理状态
        return;
    }
    // 如果没全选则全选，如果已经 全选则取消全选
    for (let i = 0; i < checkbox_items.value.length; i++) {
        checkbox_items.value[i].checked = !checkbox_items.value[i].checked;
    }

}

const removeAll = () => {
    if (!checkbox_items.value) {
        snackbar({
            message: "没有可选的单词",
        });
        isManyManage.value = false; // 取消批量管理状态
        return;
    }
    const selectedIds = checkbox_items.value.filter(item => item.checked).map(item => item.value);
    if (selectedIds.length === 0) {
        snackbar({
            message: "请至少选择一个单词",
        });
        isManyManage.value = false; // 取消批量管理状态
        return;
    }

    confirm({
        headline: "删除单词",
        description: `确定要删除 ${selectedIds.length} 个单词吗？`,
        confirmText: "删除",
        cancelText: "取消",
        onConfirm: () => {
            // 批量删除选中的单词
            selectedIds.forEach(id => {
                const index = words.findIndex(item => item._id === id);
                if (index !== -1) {
                    words.splice(index, 1);
                }
            });
            snackbar({
                message: "已删除选中的单词",
            });
            if (words.length === 0) {
                nowFoc.value = -1;
            } else {
                nowFoc.value = Math.min(nowFoc.value, words.length - 1);
            }
        }
    })
    isManyManage.value = false; // 取消批量管理状态
}

const chnageWord = (wid, id, type) => {
    //const wordItem = words.flatMap(item => item.data).find(item => item._id === id);
    const wordItem = words.find(item => item._id === wid)?.data.find(item => item._id === id);
    if (!wordItem) {
        snackbar({
            message: "单词未找到",
        });
        return;
    }
    prompt({
        headline: "修改单词",
        description: `请输入新的${type === 'word' ? '单词' : '翻译'}`,
        confirmText: "确定",
        cancelText: "取消",
        textFieldOptions: {
            value: wordItem[type] || '',
        },
        onConfirm: (value) => {
            if (!value) {
                snackbar({
                    message: "请输入单词",
                });
                return;
            }
            wordItem[type] = value;
        }, onOpened: (dialog) => {
            dialog.querySelector('mdui-text-field').focus(); // 打开对话框时自动聚焦输入框
            dialog.querySelector('mdui-text-field').setSelectionRange(0, wordItem[type].length); // 选中输入框内容
        }
    });
}

const SaveAll = () => {
    return new Promise((resolve, reject) => {
        // 判断是否有data.length为0的单词
        const emptyWords = words.filter(item => item.data.length === 0);
        if (emptyWords.length > 0) {
            snackbar({
                message: "请删除没有单词的单词组",
            });
            reject()
            return;
        }
        fetch(`${window.server}/api/change_word`, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({ word_sheet_id: id, word: words })
        })
            .then(response => response.json())
            .then(data => {
                if (data.message === "插入成功") {
                    snackbar({
                        message: "保存成功",
                    });
                    isManyManage.value = false; // 取消批量管理状态
                    resolve();
                } else {
                    snackbar({
                        message: data.message || "保存失败",
                    });
                    reject();
                }
            })
            .catch(error => {
                console.error("请求错误:", error)
                snackbar({
                    message: "请求错误，请稍后再试",
                });
                reject();
            })

    });
}

</script>

<style scoped>
main {
    width: 100%;
    height: 100%;
    overflow-y: auto;
    overflow-x: hidden;
    scroll-behavior: smooth;
    position: relative;
}

.mdui-list-item-woed {
    font-size: 15px;
    display: flex;
    flex-direction: row;
    gap: 10px;
    align-items: center;
    margin-bottom: 10px;
    line-height: normal;
}

.list-item-woed {
    border-bottom: 1px solid #e0e0e0;

    display: flex;
    align-items: center;
    justify-content: space-between;
    box-sizing: border-box;
    margin-bottom: 10px;
    opacity: 0;
    animation: fadeIn 0.3s ease forwards;
    height: auto;


    .right-btn {
        transition: all 0.3s ease;
        width: 60px;
        height: 100%;
        display: flex;
        align-items: center;
        justify-content: center;
        flex-direction: column;
        gap: 5px;
        padding-top: 5px;
        padding-bottom: 5px;
    }

    .left-btn {
        transition: all 0.3s ease;
        width: 60px;
        height: 100%;
        display: flex;
        align-items: center;
        justify-content: center;
        flex-direction: column;
        transform: scale(0);
        transform-origin: left;
        opacity: 0;
        filter: blur(5px);
    }

    .content {
        transition: transform 0.3s ease;
        flex-grow: 1;
        padding: 10px;
        box-sizing: border-box;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
        transform: translateX(-60px);
    }
}

.left-btn-hide {
    transform: scale(1) !important;
    opacity: 1 !important;
    filter: blur(0) !important;
}

.content-is-mm {
    transform: translateX(0) !important;
}

.highlight {
    background-color: #e0e0e0;
}


@keyframes fadeIn {
    from {
        opacity: 0;
    }

    to {
        opacity: 1;
    }

}


.more_border_btn {
    border-radius: 8px 30px 30px 8px !important;

    transform: translateX(0px) !important;
}

.more_border_all {
    border-radius: 30px 8px 8px 30px !important;

    transform: translateX(-8px) scale(1) !important;
    opacity: 1 !important;
    pointer-events: auto !important;

    filter: blur(0) !important;
}

.more_rem_btn {

    border-radius: 8px 8px 8px 8px !important;
    transform: translateX(-4px) scale(1) !important;
    opacity: 1 !important;
    filter: blur(0) !important;
    pointer-events: auto !important;
}

.mm_rem_btn {
    transition: all 0.3s ease, transform 0.3s cubic-bezier(0.34, 1.56, 0.64, 1);
    transition-delay: 50ms;
    border-radius: 30px 30px 30px 30px;
    transform: translateX(80px);
    z-index: 1;
    opacity: 0.2;
    pointer-events: auto;
    filter: blur(5px);
}

.mm_btn {
    transition: all 0.3s ease;
    border-radius: 30px 30px 30px 30px;

    transform: translateX(0px);
    z-index: 3;
}

.mm_all_btn {
    transition: all 0.3s ease, transform 0.3s cubic-bezier(0.34, 1.56, 0.64, 1);
    transition-delay: 70ms;
    border-radius: 30px 30px 30px 30px;
    opacity: 0;
    pointer-events: none;
    z-index: 2;
    transform: scale(0.8) translateX(160px);
    filter: blur(5px);
}

.bor {
    position: absolute;
    border: 2px solid rgba(94, 94, 94, 0.582);
    filter: blur(0.5px);
    box-sizing: border-box;
    border-radius: 10px;
    background-color: #8f8f8f0c;
    backdrop-filter: blur(0.1px);
    pointer-events: none;
    top: 0;
    left: 0;

}
</style>